<?php

namespace falcon5\inc\Http\Controllers;

use falcon5\inc\Exceptions\InvalidArgumentException;
use falcon5\inc\Exceptions\RemoteServiceException;
use falcon5\inc\Http\JsonResponse;
use falcon5\inc\Http\Request;
use falcon5\inc\Infrastructure\Services\CacheService;
use falcon5\inc\Infrastructure\Services\Falcon5Service;
use lucatume\DI52\ContainerException;

/**
 * Class CacheController
 * @package falcon5\inc\Http\Controllers
 */
class CacheController extends BaseController
{

    /**
     * fetch cache list
     * @param Request $request
     * @return JsonResponse
     * @throws InvalidArgumentException
     * @throws RemoteServiceException
     * @throws ContainerException
     */
    public function list(Request $request): JsonResponse
    {
        $keyword = (string)$request->get('keyword', '');
        $lang = (string)$request->get('language', '');
        $page = (int)$request->get('page', 1);
        $pageSize = (int)$request->get('page_size', 10);

        /** @var CacheService $cacheService */
        $cacheService = falcon5_app(CacheService::class);
        $data = $cacheService->fetchList($keyword, $lang, $page, $pageSize);

        return JsonResponse::success($data);
    }

    /**
     * lock page
     * @param Request $request
     * @return JsonResponse
     * @throws ContainerException
     * @throws RemoteServiceException|\hollisho\helpers\InvalidArgumentException
     */
    public function lockPage(Request $request): JsonResponse
    {
        $cacheId = (int)$request->get('cache_id');
        $pageId = (int)$request->get('page_id');

        if (!$pageId || !$cacheId) {
            return JsonResponse::error(400, 'Invalid page or cache ID');
        }

        /** @var Falcon5Service $service */
        $cacheService = falcon5_app(CacheService::class);
        $cacheService->lockPage($cacheId);
        $result=[];
        $result["extra"]['is_locked'] = 1;
        $result["code"]=1;
        return $this->handleServiceResponse($result);
    }

    /**
     * unlock page
     * @param Request $request
     * @return JsonResponse
     * @throws ContainerException
     * @throws RemoteServiceException
     * @throws \hollisho\helpers\InvalidArgumentException
     */
    public function unlockPage(Request $request): JsonResponse
    {
        $cacheId = (int)$request->get('cache_id');
        $pageId = (int)$request->get('page_id');

        if (!$pageId || !$cacheId) {
            return JsonResponse::error(400, 'Invalid page or cache ID');
        }

        /** @var Falcon5Service $service */
        $cacheService = falcon5_app(CacheService::class);
        $cacheService->unlockPage($cacheId);
        $result=[];
        $result["extra"]['is_locked'] = 0;
        $result["code"]=1;
        return $this->handleServiceResponse($result);
    }
}